package com.customization.huangwm.workflowNodeAction.lims;

import com.customization.huangwm.utils.DateTools;
import com.customization.huangwm.utils.LogTool;

import com.alibaba.fastjson.JSONObject;
import com.customization.huangwm.utils.HttpRequest;

import org.springframework.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.axis.components.logger.LogFactory;

public class SamplingInfoToLims extends BaseBean implements Action {
    private LogTool log = new LogTool("/log/Lims/huangwm/action/SamplingInfoToLims", false);
    private DateTools dateTools = new DateTools();
    private HttpRequest http = new HttpRequest();
    private static Map<String, String> allWeatherStr = new HashMap<String, String>();
    private static Map<String, String> allCharacterStr = new HashMap<String, String>();

    //1 初始化天气
    static {
        allWeatherStr.put("0", "晴");
        allWeatherStr.put("1", "雨");
        allWeatherStr.put("2", "陰");
        allWeatherStr.put("3", "霧");
        allWeatherStr.put("4", "雷暴");
        allWeatherStr.put("5", "大風");
        allWeatherStr.put("6", "霧霾");
        allWeatherStr.put("7", "其他");

        allCharacterStr.put("0", "無色澄清");
        allCharacterStr.put("1", "微黃微濁");
        allCharacterStr.put("2", "黃或渾濁");
        allCharacterStr.put("3", "其他");
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        log.writeLog("LIMS 采樣記錄流程推送lims requestid=" + requestInfo.getRequestid());
        JSONObject reqData = new JSONObject();
        reqData.put("plantCode", "01");
        reqData.put("action", "storeSamplingData");

        List<JSONObject> headerData = new ArrayList<>();

        List<JSONObject> instruments = new ArrayList<>();

        //Map<String,String> mainTable = new HashMap<String, String>();
        Property[] properties = requestInfo.getMainTableInfo().getProperty();
        for (int i = 0; i < properties.length; i++) {
            JSONObject instruments_id = new JSONObject();//仪器id

            if (properties[i].getName().equals("LimsNo")) {
                //mainTable.put(properties[i].getName(),properties[i].getValue());
                reqData.put("taskId", properties[i].getValue());
            }
            //01 采样日期
            else if (properties[i].getName().equals("SamplingDate")) {
                JSONObject header_data = new JSONObject();
                //mainTable.put(properties[i].getName(),properties[i].getValue());
                header_data.put("name", "采樣日期");
                header_data.put("type", "3");
                header_data.put("value", properties[i].getValue());
                headerData.add(header_data);
            }
            //02 采样人员
            else if (properties[i].getName().equals("SamplingOperator")) {
                //对应userCode
                reqData.put("userCode", getUserValue(properties[i].getValue(), "workcode"));
                JSONObject header_data = new JSONObject();
                //mainTable.put(properties[i].getName(),properties[i].getValue());
                header_data.put("name", "采樣人員");
                header_data.put("type", "0");
                header_data.put("value", getUserValue(properties[i].getValue(), "lastname"));
                headerData.add(header_data);
            }
            //03 天气
            else if (properties[i].getName().equals("Weather")) {
                JSONObject header_data = new JSONObject();
                //mainTable.put(properties[i].getName(),properties[i].getValue());
                header_data.put("name", "天氣");
                header_data.put("type", "0");
                header_data.put("value", getWeatherStr(properties[i].getValue()));
                headerData.add(header_data);
            }
            //04 儀器編號1 对应餘氯儀編號
            else if (properties[i].getName().equals("ResidualChlorineMeterNo")) {
                JSONObject header_data = new JSONObject();
                //mainTable.put(properties[i].getName(),properties[i].getValue());
                header_data.put("name", "儀器編號1");
                header_data.put("type", "0");
                header_data.put("value", getIntrumentCode(properties[i].getValue()));
                headerData.add(header_data);

                instruments_id.put("id", getIntrumentID(properties[i].getValue()));
                instruments.add(instruments_id);
            }
            //05 儀器編號2 对应温度计編號
            else if (properties[i].getName().equals("ThermometerNo")) {
                JSONObject header_data = new JSONObject();
                //mainTable.put(properties[i].getName(),properties[i].getValue());
                header_data.put("name", "儀器編號2");
                header_data.put("type", "0");
                header_data.put("value", getIntrumentCode(properties[i].getValue()));
                headerData.add(header_data);

                instruments_id.put("id", getIntrumentID(properties[i].getValue()));
                instruments.add(instruments_id);
            }
            //06 餘氯方法
            else if (properties[i].getName().equals("ResidualChlorine")) {
                JSONObject header_data = new JSONObject();
                //mainTable.put(properties[i].getName(),properties[i].getValue());
                header_data.put("name", "餘氯方法");
                header_data.put("type", "0");
                header_data.put("value", properties[i].getValue());
                headerData.add(header_data);
            }
            //07 溫度方法
            else if (properties[i].getName().equals("Temperature")) {
                JSONObject header_data = new JSONObject();
                //mainTable.put(properties[i].getName(),properties[i].getValue());
                header_data.put("name", "溫度方法");
                header_data.put("type", "0");
                header_data.put("value", properties[i].getValue());
                headerData.add(header_data);
            }
        }
        reqData.put("headerData", headerData);
        reqData.put("instruments", instruments);

        List<JSONObject> sampleDatas = new ArrayList<>();
        //2 获取明细内容
        String tableName = requestInfo.getRequestManager().getBillTableName();
        String billid = requestInfo.getRequestManager().getBillid() + "";
        RecordSet rs = new RecordSet();
        rs.execute("select * from " + tableName + "_dt1 where mainid=" + billid);
        log.writeLog("获取明细内容组成 sampleData");
        while (rs.next()) {
            JSONObject datas = new JSONObject();

            String sampleId = rs.getString("simpleid");
            datas.put("sampleId", sampleId);

            String delete_tag = rs.getString("delete_tag");

            datas.put("deleted", delete_tag.isEmpty() ?"0":delete_tag);

            List<JSONObject> sampleData = new ArrayList<>();//用于存放sampleData下的data

            JSONObject data1 = new JSONObject();
            //sampleData里的data固定数量9个 根据lims接口做适应性调整
            String SamplingTime = rs.getString("SamplingTime");//采样时间
            data1.put("name", "采樣時間");
            data1.put("type", "0");
            data1.put("value", SamplingTime);
            sampleData.add(data1);

            JSONObject data2 = new JSONObject();
            String SamplingLocation = rs.getString("SamplingLocation");//採樣地點
            data2.put("name", "采樣地點");
            data2.put("type", "0");
            data2.put("value", SamplingLocation);
            sampleData.add(data2);

            JSONObject data3 = new JSONObject();
            String SampleNo = rs.getString("SampleNo");//樣品編號

            JSONObject data4 = new JSONObject();
            String BottleNumber = rs.getString("BottleNumber");//瓶號
            data4.put("name", "採樣瓶號");
            data4.put("type", "0");
            data4.put("value", getBottleNumberStrV2(BottleNumber,tableName));
            sampleData.add(data4);

            JSONObject data5 = new JSONObject();
            String ResidualChlorine = rs.getString("ResidualChlorine");
            //data5.put("name", "Residual Chlorine");
            data5.put("name", "餘氯");
            data5.put("type", "0");
            String r = "";
            if(!ResidualChlorine.isEmpty()){
                r = String.valueOf(Double.parseDouble(ResidualChlorine));
            }
            data5.put("value", ResidualChlorine.equals("")?"":r.length()==3?r+"0":r);
            sampleData.add(data5);

            JSONObject data6 = new JSONObject();
            String TotalChlorine = rs.getString("TotalChlorine");
            //data6.put("name", "Total Chlorine");
            data6.put("name", "總氯");
            data6.put("type", "0");
            String t1 = "";
            if(!TotalChlorine.isEmpty()){
                t1 = String.valueOf(Double.parseDouble(TotalChlorine));
            }
            data6.put("value", TotalChlorine.equals("")?"":t1.length()==3?t1+"0":t1);
            sampleData.add(data6);

            JSONObject data7 = new JSONObject();
            String WaterTemperature = rs.getString("WaterTemperature");
            //data7.put("name", "Temperature");
            data7.put("name", "溫度");
            data7.put("type", "0");
            String w ="";
            if(!WaterTemperature.isEmpty()){
                w = String.valueOf(Double.parseDouble(WaterTemperature));
            }
            data7.put("value", WaterTemperature.equals("")?"":w.length()==3?w+"0":w);
            sampleData.add(data7);

            JSONObject data8 = new JSONObject();
            String Temperature = rs.getString("Temperature");
            data8.put("name", "氣溫");
            data8.put("type", "0");
            String t ="";
            if(!Temperature.isEmpty()){
                t = String.valueOf(Double.parseDouble(Temperature));
            }
            data8.put("value", Temperature.equals("")?"":t.length()==3?t+"0":t);
            sampleData.add(data8);

            JSONObject data9 = new JSONObject();
            String Character = rs.getString("Character");//性狀
            String CharacterOther = rs.getString("CharacterOther");//其他性状
            data9.put("name", "樣品狀態");
            data9.put("type", "0");
            data9.put("value", Character.equals("3") ? CharacterOther : getCharacterStr(Character));
            sampleData.add(data9);

            JSONObject data10 = new JSONObject();
            String SamplingContainer = rs.getString("SamplingContainer");//採樣容器
            data10.put("name", "採樣容器類別");
            data10.put("type", "0");
            data10.put("value", getSamplingContainerStr(SamplingContainer));
            sampleData.add(data10);

            datas.put("data", sampleData);

            sampleDatas.add(datas);//将这一行数据添加到sampleData
        }
        reqData.put("sampleData", sampleDatas);

        List<JSONObject> attachments = new ArrayList<>();//这个暂时为空
        attachments.add(JSONObject.parseObject("{\"fileName\":\"\",\"fileData\":\"\"}"));
        reqData.put("attachments", attachments);

        JSONObject allParams = new JSONObject();//所有的请求参数
        allParams.put("reqNb", dateTools.getTimestamp());
        allParams.put("reqLang", "zh");
        String token = getPropValue("LIMS", "eop_reqToken").isEmpty() ? "EapLims20200708D1207F4TEST" : getPropValue("LIMS", "eop_reqToken");
        String url = getPropValue("LIMS", "eop_reqToken").isEmpty() ? "https://testeop.macaowater.com" : getPropValue("LIMS", "eop_reqUrl");
        allParams.put("reqToken", token);
        allParams.put("reqData", reqData);
        log.writeLog("请求参数>>>" + JSONObject.toJSONString(allParams));
        try{
            JSONObject requestResult = http.CallApiPost(url+"/eop/eapToLims/eapapi", JSONObject.toJSONString(allParams));
            log.writeLog("请求结果>>>" + JSONObject.toJSONString(requestResult));

            if (!requestResult.get("state").equals("0") || requestResult==null) {
                requestInfo.getRequestManager().setMessageid(requestInfo.getRequestid());
                requestInfo.getRequestManager().setMessagecontent(requestResult.get("msg").toString());
                return FAILURE_AND_CONTINUE;
            }
        }catch (Exception e){
            requestInfo.getRequestManager().setMessageid(requestInfo.getRequestid());
            requestInfo.getRequestManager().setMessagecontent("http error"+e.getMessage());
            return FAILURE_AND_CONTINUE;
        }
        return SUCCESS;
    }

    /**
     * 根据天气的选项值返回具体天气字符串
     * @param weather
     * @return
     */
    public String getWeatherStr(String weather) {
        if (weather.isEmpty()) return "";
        StringBuffer weatherStr = new StringBuffer();
        String[] weatherIndex = weather.split(",");
        for (int i = 0; i < weatherIndex.length; i++) {
            String index = weatherIndex[i];
            for (Entry<String, String> entry : allWeatherStr.entrySet()) {
                if (entry.getKey().equals(index)) {
                    weatherStr.append("," + entry.getValue());
                }
            }
        }
        return weatherStr.toString().substring(1, weatherStr.length());
    }

    /**
     * 根据用户Id和获取的字段查询人员表获取字段值
     * @param userid
     * @param field
     * @return
     */
    public String getUserValue(String userid, String field) {
        if (userid.isEmpty() || field.isEmpty()) return "";
        RecordSet rs = new RecordSet();
        String sql = "select " + field + " from HrmResource where id=" + userid;
        rs.execute(sql);
        log.writeLog("getUserValue>" + sql);
        if (rs.next()) {
            return rs.getString(field);
        }
        return "";
    }

    /**
     * 根据浏览按钮Id查询uf_SamplingISM表中的code
     * @param id
     * @return
     */
    public String getIntrumentCode(String id) {
        if (id.isEmpty()) return "";
        RecordSet rs = new RecordSet();
        String sql = "select code from uf_SamplingISM where id=" + id;
        log.writeLog("getIntrumentCode>" + sql);
        rs.execute(sql);
        if (rs.next()) {
            return rs.getString("code");
        }
        return "";
    }

    /**
     * 根据浏览按钮Id查询uf_SamplingISM表中的outkey
     * @param id
     * @return
     */
    public String getIntrumentID(String id) {
        if (id.isEmpty()) return "";
        RecordSet rs = new RecordSet();
        String sql = "select outkey from uf_SamplingISM where id=" + id;
        log.writeLog("getIntrumentID>" + sql);
        rs.execute(sql);
        if (rs.next()) {
            return rs.getString("outkey");
        }
        return "";
    }

    /**
     * 根据样品性状选择框id返回具体名称
     * @param character
     * @return
     */
    public String getCharacterStr(String character) {
        if (character.isEmpty()) return "";
        String characterStr = "";
        for (Entry<String, String> entry : allCharacterStr.entrySet()) {
            if (entry.getKey().equals(character)) {
                characterStr = entry.getValue();
            }
        }
        return characterStr;
    }

    /**
     * 返回采样容器
     * @param samplingContainer
     * @return
     */
    public String getSamplingContainerStr(String samplingContainer) {
        if (samplingContainer.isEmpty()) return "";
        String SamplingContainerStr = "";
        if (samplingContainer.equals("0")) {
            SamplingContainerStr = "日(Ⅰ)";
        } else if (samplingContainer.equals("1")) {
            SamplingContainerStr = "周(Ⅱ)";
        } else {
            SamplingContainerStr = "月(Ⅲ)";
        }
        return SamplingContainerStr;
    }

    /**
     * 返回采样瓶号
     * @param bottleNumber
     * @return
     */
    public String getBottleNumberStr(String bottleNumber) {
        if (bottleNumber.isEmpty()) return "";
        String bottleNumberStr = "";
        if (bottleNumber.equals("0")) {
            bottleNumberStr = "Ⅰ";
        } else if (bottleNumber.equals("1")) {
            bottleNumberStr = "Ⅱ";
        } else {
            bottleNumberStr = "Ⅲ";
        }
        return bottleNumberStr;
    }

    /**
     * 返回采样瓶号
     * @param bottleNumber
     * @return
     */
    public String getBottleNumberStrV2(String bottleNumber,String tableName) {
        if (bottleNumber.isEmpty()) return "";
        String bottleNumberStr = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from workflow_billfield where detailtable ='"+tableName+"_dt1' and fieldname='BottleNumber'");
        if(rs.next()){
            int fieldid = rs.getInt("id");
            rs.executeQuery("select * from  workflow_selectitem where fieldid="+fieldid +" and SELECTVALUE="+bottleNumber);
            if(rs.next()){
                bottleNumberStr = rs.getString("selectname");
            }else{
                return "null";
            }
            return bottleNumberStr;
        }else{
            return "null";
        }
    }
}
